package com.cars.satoken.service.impl;


import cn.dev33.satoken.stp.StpInterface;
import com.cars.satoken.entities.Permission;
import com.cars.satoken.entities.Role;
import com.cars.satoken.entities.User;
import com.cars.satoken.service.PermissionService;
import com.cars.satoken.service.RoleService;
import com.cars.satoken.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限加载接口实现类
 *
 * @author: caoqianfan
 * @date: 2023/9/27 15:26
 */
@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;

    /**
     * 返回一个账号所拥有的权限码集合
     *
     * @param loginId   loginId
     * @param loginType loginType
     * @return {@code List<String>}
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        User user = userService.getById((Long) loginId);
        List<String> list = new ArrayList<>();
        for (Long id : user.getPermissionId()) {
            Permission permission = permissionService.getById(id);
            list.add(permission.getName());
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     *
     * @param loginId   loginId
     * @param loginType loginType
     * @return {@code List<String>}
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        User user = userService.getById((Long) loginId);
        List<String> list = new ArrayList<String>();
        for (Long id : user.getRoleId()) {
            Role role = roleService.getById(id);
            list.add(role.getName());
        }
        return list;
    }

}